#include <SoftwareSerial.h>
#include <MsTimer2.h>

#define LED_Pin 12
#define GLED_Pin 11
#define KEY_Pin 2
#define UART_TX_Pin 1
#define UART_RX_Pin 0
#define MAXNUM 100

/* 软件串口对象 */
SoftwareSerial mySerial(7, 8);
char buff[MAXNUM] = "";
int recv_num = 0;

/* 清除缓冲区数据和buff数据 */
void clear_serial() {
  char i;
  int buff_i = 0;
  /* 清除接收缓冲区 */
  do{
    i = Serial.read();
  }while(i != -1);
  /* 清除buff */
  for(int i=0; i<MAXNUM; i++){
    buff[MAXNUM] = "";
  }
}

/* 将接收缓冲区的数据转移到buff中
 */
void printf_buff(){
  int buff_length = Serial.available();
  Serial.readBytes(buff, buff_length);
  mySerial.println(buff);
}

/* ESP8266初始化函数
 */
void ESP8266_INIT(){
  Serial.write("AT+RST\r\n");
  delay(1000);
  digitalWrite(LED_Pin, LOW);
  
  /* 复位正常 */
  clear_serial();
  Serial.write("AT\r\n");
  delay(100);
  while(!(Serial.find("OK")));
  
  /* AT正常 */
  clear_serial();
  Serial.write("AT+CWMODE=2\r\n");
  delay(100);
  while(!(Serial.find("OK")));
  
  /* CWMODE正常 */
  clear_serial();
  Serial.write("AT+CWSAP=\"FuckMe\",\"123123abc\",1,3\r\n");
  delay(100);
  while(!(Serial.find("OK")));
  
  /* 开启热点正常 */
  clear_serial();
  Serial.write("AT+CIPMUX=1\r\n");
  delay(100);
  while(!(Serial.find("OK")));
  
  /* 多连接模式正常 */
  clear_serial();
  Serial.write("AT+CIPSERVER=1,8080\r\n");
  delay(100);
  while(!(Serial.find("OK")));
  
  /* 服务器模式正常 */
  clear_serial();
  Serial.write("AT+CIPSTO=5000\r\n");
  delay(100);
  while(!(Serial.find("OK")));
  
  /* CIPSTO正常 */
  clear_serial();
  mySerial.println("***********************************");
}

/* 定时器中断 */
void Timer_INTR(){
  if(Serial.available() != 0){
    printf_buff();
    /* 接收缓冲区有"LON" */
    if(strstr((char*)buff, "ON") != NULL)
    {
      digitalWrite(GLED_Pin, HIGH);
    }
    /* 接收缓冲区有"LOFF" */
    else if(strstr((char*)buff, "OFF") != NULL)
    {
      digitalWrite(GLED_Pin, LOW);
    }
    clear_serial();
  }
}

void setup() {
  pinMode(LED_Pin, OUTPUT);
  pinMode(GLED_Pin, OUTPUT);
  digitalWrite(LED_Pin, HIGH);
  digitalWrite(GLED_Pin, LOW);

  delay(5000);
  /* 设置硬件串口 */
  Serial.begin(115200);
  Serial.setTimeout(100);
  /* 设置软件串口 */
  mySerial.begin(115200);
  mySerial.println("Hello, world?");

  /* 配置定时器中断 */
  MsTimer2::set(200, Timer_INTR);
  while(!Serial);
  /* 初始化esp8266 */
  ESP8266_INIT();
  /* 开启定时器中断 */
  MsTimer2::start();
}

void loop() {
  /* 小灯闪烁 */
  digitalWrite(LED_Pin, HIGH);
  delay(500);
  digitalWrite(LED_Pin, LOW);
  delay(500);
}
